/* 
 * Copyright (C) 2022 Leah Rowe <info@minifree.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "../include/lib/mac.h"

int parseMacAddress(char* strMacAddress, uint8_t** mac)
{
	uint8_t value;
	uint16_t value16;
	uint16_t i, j;
	uint8_t* nibble = (uint8_t*) malloc(256);
	if(nibble==NULL) {
		printf("E: could not allocate enough memory.\n");
		return 0;
	}

	if (strMacAddress == NULL) goto fail;
	if (strlen(strMacAddress) != 17) goto fail;

	for (i=0; i<256; i++) nibble[i] |= 0xFF;
	for (i=97; i<103; i++) nibble[i] = (uint8_t)i - 87;
	for (i=65; i<71; i++) nibble[i] = (uint8_t)i - 55;
	for (i=48; i<59; i++) nibble[i] = (uint8_t)i - 48;

	for(i=2; i<14; i+=3)
		if(strMacAddress[i]!=':') goto fail;

	for(i=0;i<3;i++) setWord(mac, i, 0, 0);

	for(i=0; i<6; i++) {
		for(j=0; j<2; j++) {
			value = nibble[(uint8_t)strMacAddress[(i*3)+j]];
			if (value > 15) goto fail;
			value16 = word(mac, i>>1, 0);
			value16 |= (value << ((j^1)<<2)) << ((i%2)<<3);
			setWord(mac, i>>1, 0, value16);
		}
	}

	free(nibble);
	return 1;
fail:
	printf("E: Invalid MAC address given.\n\n");
	free(nibble);
	return 0;
}

int setMacAddressInParts(uint8_t** buffer, uint8_t** mac)
{
	uint8_t success = 0;

	for (uint8_t i=0; i<2; i++) {
		if (validChecksumInPart(buffer,i)) {
			memcpy((*buffer) + (i << 12), (*mac), 6);
			setChecksumInPart(buffer,i);
			success = 1;
		}
	}
	if (!success) goto fail;

	printf("MAC address successfully updated.\n");
	return 1;
fail:
	printf("E: Bad checksums. MAC addresses not updated.\n\n");
	return 0;
}
